<?php

namespace App\Models;

use App\Models\Traits\ModelTree;
use Encore\Admin\Traits\AdminBuilder;
use Illuminate\Database\Eloquent\Builder;

class Cate extends BaseModel
{
    use ModelTree, AdminBuilder;

    /**
     * 与模型关联的表名
     * @var string
     */
    protected $table = 'cates';





    protected $hidden = [];

    /**
     * $fillable可以被批量赋值的属性.   $guarded为不能批量赋值
     * @var array
     */
    protected $guarded = ['id', 'mslug'];

    protected $includes = ['posts', 'posts.user'];

    protected $hiddenFields = ['mslug'];

    protected $withSet = [
        'posts' => [
            'query' => 1,
            'sort' => '-id',
            'fields' => 'id,user_id,cate_id,title',
            'hidden_fields' => 'content,none',
        ],
        'posts.user' => [
            'fields' => 'id,name'
        ]
    ];

    protected $queryInit = ['include' => 'posts,posts.user', 'fields' => 'id,name,title'];

    protected $ignoreCreate = ['mslug'];
    protected $ignoreUpdate = ['mslug'];

    /**
     * 属性类型转.
     * @var array
     */
    protected $casts = ['sets' => 'json'];

    //复用表
    public function __construct(array $attributes = [])
    {
        parent::__construct($attributes);
        static::addGlobalScope("avaiable", function (Builder $builder) {
            $builder->where('mslug', get_class($this));
        });
        $this->setAttribute('mslug', get_class($this));
    }

    //复用表，防错误追加,强制设置
    public function setMslugAttribute($value)
    {
        $this->attributes['mslug'] = get_class($this);
    }

    public function getGroupsAttribute($value)
    {
        if (!empty($value)) {
            $value = str2arr($value);
        } else {
            $value = [];
        }
        return $value;
    }

    /**
     * 关联
     */
    public function posts()
    {
        return $this->hasMany(Post::class);
    }

    /**
     * scope
     */
    public function scopeMyTest($query, $id)
    {
        return $query->where('id', $id ?: 16);
    }

    public function scopeParent($query)
    {
        return $query->where('parent_id', '<', 10);
    }
}
